package com.ytzl.itrip.search.dao;

import com.ytzl.itrip.utils.common.Constants;
import com.ytzl.itrip.utils.common.EmptyUtils;
import com.ytzl.itrip.utils.common.Page;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;

import java.io.IOException;
import java.util.List;

/**
 * Created by Admin on 2018/4/27.
 */
public class BaseQuery<T> {
    private HttpSolrClient solrClient;

    public BaseQuery(String baseUrl){
        solrClient=new HttpSolrClient(baseUrl);
        solrClient.setParser(new XMLResponseParser());
        solrClient.setConnectionTimeout(1000);

    }

    public Page<T> queryPage(SolrQuery solrQuery, Integer no, Integer pageNo, Integer pagesize, Class clazz) throws IOException, SolrServerException {
        Integer currPage= EmptyUtils.isEmpty(pageNo)? pageNo: Constants.DEFAULT_PAGE_NO;
        Integer pSize =EmptyUtils.isEmpty(pagesize)? pagesize:Constants.DEFAULT_PAGE_SIZE;
        solrQuery.setStart((currPage-1)*pSize);
        solrQuery.setRows(pSize);
        QueryResponse queryResponse=solrClient.query(solrQuery);

        Integer totle=Long.valueOf(queryResponse.getResults().getNumFound()).intValue();

        Page<T> page = new Page<>(currPage,pagesize,totle);
        List<T> rows=queryResponse.getBeans(clazz);
        page.setRows(rows);

        return  page;
    }

    public  List<T> queryList(SolrQuery solrQuery,Integer pagesize,Class clazz) throws IOException, SolrServerException {
        if (EmptyUtils.isNotEmpty(pagesize)){
            solrQuery.setStart(0);
            solrQuery.setRows(pagesize);
        }
        QueryResponse queryResponse=solrClient.query(solrQuery);
        return  queryResponse.getBeans(clazz);
    }
}
